package com.wyj.quartz;

import com.wyj.pojo.DiscussPost;
import com.wyj.service.imp.CommentServiceImp;
import com.wyj.service.imp.DiscussPostServiceImp;
import com.wyj.service.imp.ElasticsearchServiceImp;
import com.wyj.service.imp.LikeServiceImp;
import com.wyj.util.CommunityConstant;
import com.wyj.util.RedisKeyUtil;
import com.wyj.util.RedisUtil;
import lombok.extern.log4j.Log4j2;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.RedisTemplate;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Set;

/**
 * @author 王永杰
 * @Description:定时要执行的业务逻辑
 * @since 2022/8/12
 */

@Log4j2
public class PostScoreRefreshJob implements Job, CommunityConstant {

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    ElasticsearchServiceImp elasticsearchServiceImp;

    @Autowired
    DiscussPostServiceImp discussPostServiceImp;

    @Autowired
    CommentServiceImp commentServiceImp;

    @Autowired
    LikeServiceImp likeServiceImp;

    @Autowired
    RedisTemplate redisTemplate;

    private static  Date epoch;

    static {
        try {
            epoch  = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2014-10-01 12:12:12");
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        String postScore = RedisKeyUtil.getPostScore();
        Set<Object> objects = redisUtil.sGet(postScore);//获取所有帖子的id

        for (Object object : objects) {
            int postId = (int) object;
            refresh(postId);//更新帖子的分数
            redisUtil.setRemove(postScore,object);//清除每个帖子的分数，因为要有新的帖子的分数了
        }
    }

    public void refresh(int postId) {
        DiscussPost discussPost = discussPostServiceImp.getDiscussPost(postId);

        log.info("refresh"+discussPost);

        if (discussPost == null) {
            log.info("该帖子不存在");
        }
        //评论数量
        int comments = commentServiceImp.getComments(discussPost.getId(), ENTITY_TYPE_COMMENT);
        //点赞数量
        long likeCount = likeServiceImp.findEntityLikeCount(ENTITY_TYPE_COMMENT, discussPost.getId());

        //计算权重
        double w = likeCount * 10 + comments * 2;

        //分数: 帖子分数 + 天数
        double score = Math.log10(Math.max(w, 1))
                + (discussPost.getCreateTime().getTime() - epoch.getTime()) / (1000 * 3600 * 24);

        //更改帖子的分数
        discussPostServiceImp.updateDiscussPostScore(discussPost.getId(),score);
        discussPost.setScore(score);

        elasticsearchServiceImp.saveDiscussPost(discussPost);
    }

}
